﻿#ifndef WTCPCLIENT_H
#define WTCPCLIENT_H

#include "common.h"
//#include "singleton.h"
#include "networkframemanager.h"

wxDECLARE_EVENT(wxEVT_TCP_CLIENT_DATA_RECEIVED, wxCommandEvent);

class WTcpClient : public wxEvtHandler ,
                   public Singleton<WTcpClient>
{
    wxDECLARE_EVENT_TABLE();

public:
    WTcpClient(wxEvtHandler* parent);
    ~WTcpClient();

    // 连接服务器
    bool connect(wxString host, unsigned short port);
    // 断开连接
    void disconnect();
    // 检查是否已连接
    bool isConnected() const;
    // 设置是否启用重连
    inline void enableReconnect(bool isenable) { m_enableReconnect = isenable; }
    // 得到是否启用重连
    inline bool isEnableReconnect(void) { return m_enableReconnect; }
    // 设置网络处理框架
    inline void setNetworkFrameManager(NetworkFrameManager *manager) { m_NetworkFrameManager = manager; }
    // 得到网络处理框架
    inline NetworkFrameManager* getNetworkFrameManager(void) { return m_NetworkFrameManager; }

    // 发送数据
    bool Send(wxString data);
    bool SendData(int msgtype,const void* data,size_t len);

private:
    // 初始化socket
    void InitSocket();
    // socket事件处理
    void OnSocketEvent(wxSocketEvent& event);
    // 读取可用数据
    void ReadData();
    bool Send(const void* data, size_t len);

private:
    void OnHeartTimeOutTimer(wxTimerEvent& event);
    void OnReconnectTimer(wxTimerEvent& event);

private:
    wxSocketClient* m_socket;
    wxEvtHandler* m_parent;
    NetworkFrameManager *m_NetworkFrameManager;
    wxTimer *m_HeartTimeOutTimer;                      /**< 心跳定时器 */
    wxTimer *m_reconnectTimer;                         /**< 断线重连定时器 */
    bool m_enableReconnect;                            /**< 是否启用重连 */
    wxString m_serverIP;                               /**< 要连接的服务器IP */
    int m_serverPort;                                  /**< 要连接的服务器端口 */

    tagMsgHearder mMsgHearder;
    bool isProcessMsgHearder;
    int errorCount;
    wxMemoryBuffer m_buffer;
};

#endif // WTCPCLIENT_H
